import { menu } from '../../../app/decorator';
import BaseColorShap from './base/BaseColorShap';

const { ccclass, disallowMultiple, executeInEditMode } = cc._decorator;

@ccclass
@disallowMultiple()
@executeInEditMode()
@menu(__filename, '触摸形状')
export default class ColorShapTouch extends BaseColorShap {
    protected _needMiterLimit = true;
    protected _needLineCap = true;
    protected _needLineJoin = true;
    protected _needLineWidth = true;
    protected _canFill = false;

    private points: cc.Vec2[] = [];

    onEnable() {
        super.onEnable();
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    }

    onDisable() {
        super.onDisable();
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    }

    onTouchStart(event: cc.Event.EventTouch) {
        this.points.length = 0;
        const pos = event.getLocation();
        this.points.push(this.node.convertToNodeSpaceAR(pos));
    }

    onTouchMove(event: cc.Event.EventTouch) {
        const pos = event.getLocation();
        this.points.push(this.node.convertToNodeSpaceAR(pos));
        this.updateColorShap();
        this.points.shift();
    }

    clear() {
        this.points.length = 0;
        super.clear();
    }

    beforeDraw() {
        return false;
    }

    onDraw(cxt: cc.Graphics, centerX: number, centerY: number) {
        if (this.points.length === 0) return;
        cxt.moveTo(this.points[0].x + centerX, this.points[0].y + centerY);
        cxt.lineTo(this.points[1].x + centerX, this.points[1].y + centerY);
    }
}
